<template>
  <div>
    <el-row class="title">
      <el-col :span="2">
        <el-checkbox v-model="checkAllState" :indeterminate="halfState" @change="checkAllOrNone">全选</el-checkbox>
      </el-col>
      <el-col :span="11"><span class="CartDescp">商品</span></el-col>
      <el-col :span="2"><span class="CartDescp">单价</span></el-col>
      <el-col :span="6"><span class="CartDescp">数量</span></el-col>
      <el-col :span="2"><span class="CartDescp">小计</span></el-col>
      <el-col :span="1"><span class="CartDescp">操作</span></el-col>
    </el-row>
    <el-empty v-if="cartList.length === 0" description="还没有添加商品，请添加商品到购物车" style="height: 400px;"/>
    <div style="min-height: 400px" v-else>
      <el-row v-for="(cart,index) in cartList" :key="index" class="cartItem">
        <el-col :span="2">
          <el-checkbox v-model="cartStateList[index].checkState" @change="checkState"/>
        </el-col>
        <el-col :span="2">
          <el-image
              :src="'/api/file/images/' + cart.goods.picList[0].url"
              style="height: 50px;width: 50px;border-radius: 5px;"
              fit="contain"
          />
        </el-col>
        <el-col :span="5">{{ cart.goods.name }}</el-col>
        <el-col :span="4">{{ cart.goods.color }} - {{ cart.goods.version }}</el-col>
        <el-col :span="2">{{ cart.goods.price }}</el-col>
        <el-col :span="6">
          <el-input-number size="small" v-model="cart.count" :min="1" @change="updateCount(cart)"/>
        </el-col>
        <el-col :span="2">{{ cart.goods.price * cart.count }}</el-col>
        <el-col :span="1">
          <el-button type="danger" :icon="Delete" circle @click="delCartInfo(cart.id)"></el-button>
        </el-col>
      </el-row>
    </div>

    <el-row class="cartFooter">
      <el-col :span="2">
        <el-checkbox label="全选" v-model="checkAllState" :indeterminate="halfState" @change="checkAllOrNone"/>
      </el-col>
      <el-col :span="3">
        <el-link type="warning" :underline="false" @click="delCartByList(checkCartList)">删除选中商品</el-link>
      </el-col>
      <el-col :span="11">
        <el-link type="danger" :underline="false" @click="delCartByList(cartList)">清理购物车</el-link>
      </el-col>
      <el-col :span="3">已选择{{ totalCount }}件商品</el-col>
      <el-col :span="3">总价：￥{{ totalPrice }}</el-col>
      <el-col :span="2">
        <el-button type="danger" @click="goToPay" style="float: right">结算</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref} from "vue";
import cartApi from "@/api/CartApi.js";
import {Delete} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

// 存放当前用户所有购物车信息
const cartList = ref([])
// 表示全选按钮是否选中
const checkAllState = ref(false)
//  没有全选状态
const halfState = ref(false)
// 每条数据被选中的状态
const cartStateList = ref([])
// 选中商品列表
const checkCartList = ref([])
// 选中商品的总价格
const totalPrice = ref(0)
// 选中商品数量
const totalCount = ref(0)

// 全选 -- 全不选
const checkAllOrNone = () => {
//   让每个购物车项前边的多选状态和全选按钮状态保持一致
  cartStateList.value.forEach(cartState => {
    cartState.checkState = checkAllState.value
  })

//   计算总价
  getTotalPriceAndCheckCartList()
}

//  购物车项前边多选按钮状态发生变化时候调用函数
const checkState = () => {
//   设置全选按钮状态
  let count = 0
  cartStateList.value.forEach(cartState => {
    if (cartState.checkState) {
      count++
    }
  })
  if (count === cartList.value.length) {
    checkAllState.value = true
    halfState.value = false
  } else if (count === 0) {
    checkAllState.value = false
    halfState.value = false
  } else {
    halfState.value = true
  }

  if (cartList.value.length === 0) {
    halfState.value = false
    checkAllState.value = false
  }
//   计算总价
  getTotalPriceAndCheckCartList()
}

// 获取购物车信息
const getCartList = async () => {
  let resp = await cartApi.getAll();
  if (resp.code === 10000) {
    cartList.value = resp.data
  }
  // 判断当前状态
  if (cartStateList.value.length === 0) {
    // 购物车状态为空，第一次加载，全部默认不选中
    setStartCartStateList()
  } else {
    // 非第一次加载，根据之前情况判断选中情况
    setCartStateList()
  }
//   获取全选状态
  checkState()
//   获取总价
  getTotalPriceAndCheckCartList()
}

// 设置初始选中状态
const setStartCartStateList = () => {
  cartList.value.forEach(cart => {
    cartStateList.value.push({checkState: false, id: cart.id})
  })
}
// 设置选中状态
const setCartStateList = () => {
  let newCartStateList = []
  cartList.value.forEach(cart => {
    let b = 1;
    cartStateList.value.forEach(cartState => {
      if (cartState.id === cart.id) {
        newCartStateList.push(cartState)
        b++
      }
    })
    if (b !== 1) {
      cartStateList.value.push({checkState: false, id: cart.id})
    }
  })
  cartStateList.value = newCartStateList
  checkState()
}

// 计算总价和商品数量
const getTotalPriceAndCheckCartList = () => {
  // 选中购物车记录的缓存
  let checkCartListCache = []
  cartStateList.value.forEach(cartState => {
    if (cartState.checkState) {
      cartList.value.forEach(cart => {
        if (cart.id === cartState.id) {
          checkCartListCache.push(cart)
        }
      })
    }
  })

//  总价的缓存
  let totalPriceCache = 0
  let totalCountCache = 0
  checkCartListCache.forEach(cart => {
    totalPriceCache = totalPriceCache + cart.goods.price * cart.count
    totalCountCache += cart.count
  })

//   将缓存中数据转移到正式数据中
  totalPrice.value = totalPriceCache
  totalCount.value = totalCountCache
  checkCartList.value = checkCartListCache
}

// 根据id删除
const delCartInfo = (id) => {
  cartApi.delInfo(id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          // 刷新购物车
          getCartList()
          // cartList.value = cartList.value.filter(cart => cart.id !== id)
          // 设置全选按钮状态
          checkState()
        } else {
          ElMessage.error(resp.msg)
          // 刷新购物车
          getCartList()
        }
      })
}

// 批量删除（删除选中的商品）
const delCartByList = (cartList) => {
  cartList.forEach(cart => {
    delCartInfo(cart.id)
  })
}

// 更新购物车
const updateCount = (cart) => {
  let cartInfo = {id: cart.id, count: cart.count};
  cartApi.updateInfo(cartInfo)
      .then(resp => {
        if (resp.code === 10000) {
          // 刷新购物车
          getCartList()
        } else {
          ElMessage.error(resp.msg)
          // 刷新购物车
          getCartList()
        }
      })
}

// 去结算方法
const goToPay = () => {
  if (checkCartList.value.length <= 0) {
    ElMessage({
      message: '请选择要购买的商品',
      type: 'error',
    })
    return
  }
  ElMessage({
    message: '正在准备商品，请等待',
    type: 'success',
    onClose: toCreateOrder(),
  })
}

// 去结算页面
const toCreateOrder = () => {
  //
  let cartList = checkCartList.value.map(cart => cart.id)
  router.push({
    path:'/user/order',
    query: {
      cartList
    }
  })
}

getCartList()
</script>

<style scoped>
.title .cartFooter {
  margin: 20px 0px;
  padding-left: 10px;
  font-size: 14px;
  background-color: #FFFFFF;
  height: 40px;
  line-height: 40px;
}

.cartItem {
  margin-bottom: 5px;
  padding-left: 10px;
  font-size: 14px;
  background-color: #FFFFFF;
  height: 50px;
  line-height: 50px;
}

.title, .el-col .cartFooter, .el-col {
  padding-top: 5px;
}

</style>